package mmc.cell3;

import java.util.ArrayList;
import java.util.List;

import mmc.Constants;
import mmc.EngineObject;
import mmc.cell.CellPosition;
import mmc.cell.ServerCell;

class ServerChunk {
	CellPosition pos;
	List<ServerCell> cells;
	
	ServerChunk(CellPosition pos, byte[][][] data){
		this.pos = pos;
		
		cells = new ArrayList<ServerCell>(Constants.CHUNK_CELLS*Constants.CHUNK_CELLS*Constants.CHUNK_CELLS);
		
		for(int i=0;i<Constants.CHUNK_CELLS;i++){
			for(int j=0;j<Constants.CHUNK_CELLS;j++){
				for(int k=0;k<Constants.CHUNK_CELLS;k++){
					byte[] content = new byte[Constants.CELL_SIZE3];
					
					for(int ix=0;ix<Constants.CELL_SIZE;ix++){
						for(int jx=0;jx<Constants.CELL_SIZE;jx++){
							for(int kx=0;kx<Constants.CELL_SIZE;kx++){
								byte value = data[i*Constants.CELL_SIZE+ix][j*Constants.CELL_SIZE+jx][k*Constants.CELL_SIZE+kx];
								content[ix*Constants.CELL_SIZE2+jx*Constants.CELL_SIZE+kx] = value;
							}
						}
					}

					ServerCell c = new ServerCell(pos.x+i*Constants.CELL_SIZE,pos.y+j*Constants.CELL_SIZE,pos.z+k*Constants.CELL_SIZE,content);
					//System.out.println(" toChunk "+c);
					cells.add(c);
				}
			}
		}
		
		compress();
	}
	
	ServerChunk(CellPosition pos){
		this.pos=pos;
		cells = new ArrayList<ServerCell>(Constants.CHUNK_CELLS*Constants.CHUNK_CELLS*Constants.CHUNK_CELLS);
	}
	
	public void compress(){
		for(ServerCell c : cells)
			c.compress();
	}
	
	public boolean isContainingBlockInRange(EngineObject o, float maxDistance){
		float s = Constants.CHUNK_HALF_DIAGONAL + maxDistance;
		
		float dx = pos.x + Constants.CHUNK_BLOCKS_HALF - o.x;
		dx *= dx;
		float dy = pos.y + Constants.CHUNK_BLOCKS_HALF - o.y;
		dy *= dy;
		float dz = pos.z + Constants.CHUNK_BLOCKS_HALF - o.z;
		dz *= dz;
		
		return (dx+dy+dz) < s*s;
	}
	
	public List<ServerCell> getCells(){
		return cells;
	}
	
	@Override
	public String toString(){
		return pos.toString();
	}
}
